const Blog = require("./modules/blogModule");
const BlogType = require("./modules/blogtypeModule");
const { Op } = require("sequelize");

//发布文章
const addBlog = async (blogInfo) => {
  return await Blog.create(blogInfo, {
    include: [
      {
        model: BlogType,
        as: "category",
        attributes: ["id", "name"],
      },
    ],
  });
};
//删除文章
const deleteBlog = async (id) => {
  await Blog.destroy({
    where: { id },
    include: [
      {
        model: BlogType,
        as: "category",
        attributes: ["id", "name"],
      },
    ],
  });
  return;
};
//修改文章
const updateBlog = async (id, blogInfo) => {
  await Blog.update(blogInfo, {
    where: { id },
    include: [
      {
        model: BlogType,
        as: "category",
        attributes: ["id", "name"],
      },
    ],
  });
  return await Blog.findByPk(id);
};
//获取单篇文章
const getBlog = async (id) => {
  return await Blog.findByPk(id, {
    include: [
      {
        model: BlogType,
        as: "category",
        attributes: ["id", "name"],
      },
    ],
  });
};
//分页获取文章
const getBlogList = async (
  page = 1,
  limit = 10,
  keyword = "",
  categoryId = 0
) => {
  let where = {};
  if (keyword.replace(/\s*/g, "").length !== 0) {
    //关键字查询
    where = {
      [Op.or]: [
        { title: { [Op.like]: `%${keyword}%` } },
        { description: { [Op.like]: `%${keyword}%` } },
        // {htmlContent:{[Op.like]:`%${keyword}%`}},
      ],
    };
  }
  if (categoryId > 0) {
    where.categoryId = categoryId;
  }
  return await Blog.findAndCountAll({
    where,
    offset: (+page - 1) * +limit,
    limit: +limit,
    include: [
      {
        model: BlogType,
        as: "category",
        attributes: ["id", "name"],
      },
    ],
  });
};

//自增浏览量
const addScanNumber = async (id) => {
  const { dataValues: data } = await Blog.findByPk(id);
  await Blog.update(
    {
      scanNumber: data.scanNumber++,
    },
    {
      where: {
        id,
      },
    }
  );
};

//自增评论数量
const addCommentNumber = async (id) => {
  const data = await Blog.findByPk(id);
  data.commentNumber++;
  await data.save();
};

//自减评论数量
const reduceComentNumber = async (id) => {
  const data = await Blog.findByPk(id);
  data.commentNumber--;
  await data.save();
};

module.exports = {
  addBlog,
  deleteBlog,
  updateBlog,
  getBlog,
  getBlogList,
  addScanNumber,
  addCommentNumber,
  reduceComentNumber,
};
